package com.example.administrator.liveapp.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.MainActivity;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.bean.JsonBean;
import com.example.administrator.liveapp.bean.LoginBean;
import com.example.administrator.liveapp.utils.AlbumImagePath;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.GetJsonDataUtil;
import com.example.administrator.liveapp.utils.MD5Utils;
import com.example.administrator.liveapp.utils.SharedPrefsUtil;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册添加用户头像等个人信息activity(已经没有用了)
 */

public class PersonalInformationPage extends AppCompatActivity implements View.OnClickListener {

    private static final int ADD_NAME = 1;
    private static final int ADD_PROFESSIONAL = 2;
    private static final int ADD_SIGNATURE = 3;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private boolean isLoaded = false;
    private Thread thread;

    private TextView textData;//显示省市区
    private static final int PHOTO_CLIP = 113;//调用系统中自带的图片剪裁的请求code
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code
    private PopupWindow mPopWindow;
    private RoundedImageView imageview;//头像
    private TextView name,professional,signature;//姓名,职业,个性签名
    private String phone2;//注册手机号
    private String password;
    private String consumerId;//注册用户Id
    private SharedPrefsUtil sp;
    private LoginBean LoginBean;

    public PersonalInformationPage(){
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_information_page);
        ApplicationUtils applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        initView();
        setData();
    }

    private void setData() {
        Intent intent = getIntent();
        phone2 = intent.getStringExtra("phone2");
        password = intent.getStringExtra("password");
        consumerId = intent.getStringExtra("consumerId");
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread==null){//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;

            }
        }
    };

    private void initView() {
        textData = (TextView) findViewById(R.id.text_data);
        imageview = (RoundedImageView) findViewById(R.id.comments_head_portrait);
        name = (TextView) findViewById(R.id.name);
        professional = (TextView) findViewById(R.id.professional);
        signature = (TextView) findViewById(R.id.signature);
        findViewById(R.id.upload_picture).setOnClickListener(this);
        findViewById(R.id.btn_show).setOnClickListener(this);
        findViewById(R.id.save_title).setOnClickListener(this);
        findViewById(R.id.login_return).setOnClickListener(this);
        findViewById(R.id.rl_name).setOnClickListener(this);
        findViewById(R.id.rl_professional).setOnClickListener(this);
        findViewById(R.id.rl_signature).setOnClickListener(this);
    }
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(PersonalInformationPage.this).inflate(R.layout.uploadpopupwindow, null);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        //设置各个控件的点击响应
        TextView tv1 = (TextView)contentView.findViewById(R.id.pop_computer);
        TextView tv2 = (TextView)contentView.findViewById(R.id.pop_financial);
        TextView tv3 = (TextView)contentView.findViewById(R.id.pop_manage);
        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
        tv3.setOnClickListener(this);
        //显示PopupWindow
        View rootView = LayoutInflater.from(PersonalInformationPage.this).inflate(R.layout.personal_information_page, null);
        showPopMenu(rootView);
    }
    /**
     * 图片上传的弹出popWindow
     *
     * @param rootView
     */
    private void showPopMenu(View rootView) {
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        // 显示窗口位置
        mPopWindow.showAtLocation(rootView, Gravity.BOTTOM| Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams lp=getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.upload_picture://弹出拍照上传头像窗口
                showPopupWindow();
                break;

            case R.id.btn_show://弹出所在地选择器
                if (isLoaded){
                    ShowPickerView();
                }else {
//                    Toast.makeText(PersonalInformationPage.this,"数据暂未解析成功，请等待",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.login_return://返回
                finish();
                break;
            case R.id.save_title://保存
                upLoadFile();
                break;
            case R.id.rl_name://添加姓名
                Intent intentName = new Intent(PersonalInformationPage.this,InputBoxPage.class);
                intentName.putExtra("title","姓名");
                intentName.putExtra("result",ADD_NAME);
                intentName.putExtra("name",name.getText().toString());
                startActivityForResult(intentName,ADD_NAME);
                break;
            case R.id.rl_professional://添加职业
                Intent intentProfessional = new Intent(PersonalInformationPage.this,InputBoxPage.class);
                intentProfessional.putExtra("title","职业");
                intentProfessional.putExtra("result",ADD_PROFESSIONAL);
                intentProfessional.putExtra("name",professional.getText().toString());
                startActivityForResult(intentProfessional,ADD_PROFESSIONAL);
                break;
            case R.id.rl_signature://添加个性签名
                Intent intentSignature = new Intent(PersonalInformationPage.this,InputBoxPage.class);
                intentSignature.putExtra("title","个性签名");
                intentSignature.putExtra("result",ADD_SIGNATURE);
                intentSignature.putExtra("name",signature.getText().toString());
                startActivityForResult(intentSignature,ADD_SIGNATURE);
                break;

        }
        /**
         * 拍照,选择相册中的图片
         */
        switch (v.getId()){
            //拍照
            case R.id.pop_computer:
                mPopWindow.dismiss();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 判断存储卡是否可以用，可用进行存储
                if (hasSdcard()) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                            Environment.getExternalStorageDirectory(), "test.jpg")));
                }
                startActivityForResult(intent, FROM_CAMERA_CODE);
            break;
            //从相册中获取
            case R.id.pop_financial:
                mPopWindow.dismiss();
                Intent intent2 = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent2, FROM_ALBUM_CODE);
            break;

            case R.id.pop_manage:
                mPopWindow.dismiss();
            break;
        }
    }

    private String result;

    //将图片转换成字符串
    private void saveBitmap(Bitmap bitmap) {
        //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
        //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        result = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
    }
    /**
     * 上传用户信息到服务器
     */
    private void upLoadFile() {
        String path = "";
        if(result!=null){
            path = result;//头像地址
        }
        String urls = AppUrl.URL + AppUrl.personalInformation;
        Map<String,Object> map = new HashMap();
        map.put("consumerId",consumerId);
        map.put("consumerName",name.getText().toString());
        map.put("consumerCareer",professional.getText().toString());
        map.put("sign",signature.getText().toString());
        map.put("address",textData.getText().toString());
        if(!path.equals("")){
            map.put("file",path);
        }
        XUtils.UpLoadFile(urls,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String code = jsonObject.optString("code");
                    String message = jsonObject.optString("message");
                    if(code.equals("60000")){
                        Login();
                    }else{
                        Toast.makeText(PersonalInformationPage.this,message+"上传失败"+consumerId,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(PersonalInformationPage.this,e.getMessage()+"异常",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(PersonalInformationPage.this,ex.getMessage()+"上传错误",Toast.LENGTH_SHORT).show();
            }
        });
    }

    protected void Login(){
        sp = new SharedPrefsUtil();
        password =MD5Utils.getMd5Value(password);
        String url = AppUrl.URL+AppUrl.LoginURL;
        Map<String,String> map=new HashMap<>();
        map.put("consumerTel", phone2);
        map.put("pass", password);
        XUtils.Get(url,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String code = jsonObject.optString("code");
                    if(code.equals("4200")){
                        Gson gson = new Gson();
                        LoginBean = gson.fromJson(result, LoginBean.class);
                        sp.putStringValue(PersonalInformationPage.this,"username",phone2);
                        sp.putStringValue(PersonalInformationPage.this,"userpassword",password.toString());
                        ApplicationUtils.getInstance().loginBean = LoginBean;
                        Intent intent = new Intent();
                        intent.setClass(PersonalInformationPage.this,MainActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                        Toast.makeText(getApplicationContext(),"登录成功",Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(),"用户名或密码错误",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                LogUtil.e(ex.getMessage()+"联网请求失败");
            }
        });

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FROM_ALBUM_CODE://相册返回的code
                if (data != null) {
                    // 得到图片的全路径
                    Uri uri = data.getData();
                    String imagePath = AlbumImagePath.getPath(this, uri);
                    photoClip(data.getData());
                }
                break;

            case FROM_CAMERA_CODE://拍照返回的code
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {
                    File file = new File(Environment.getExternalStorageDirectory()
                            + "/test.jpg");
                    if (file.exists()) {
                        photoClip(Uri.fromFile(file));
                    }
                } else {
                    Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                }
                break;

            case PHOTO_CLIP://剪裁返回的code
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras!=null) {
                        Bitmap photo = extras.getParcelable("data");
                        imageview.setImageBitmap(photo);
                        if(photo!=null){
                            Toast.makeText(this, "photo不为空！", Toast.LENGTH_SHORT).show();
                            saveBitmap(photo);
                        }
                    }
                }
                break;
            default:
                break;
        }
        switch (resultCode){
            case ADD_NAME://添加姓名返回的code
                name.setText(data.getStringExtra("add"));
                break;

            case ADD_PROFESSIONAL://添加职位返回的code
                professional.setText(data.getStringExtra("add"));
                break;

            case ADD_SIGNATURE://添加个性签名返回的code
                signature.setText(data.getStringExtra("add"));
                break;
            default:
                break;
        }
    }

    private void photoClip(Uri uri) {
        // 调用系统中自带的图片剪裁
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_CLIP);
    }

    public boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }




    /**
     * 省市区3级选择器
     */
    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView  pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()+
                        options2Items.get(options1).get(options2)+
                        options3Items.get(options1).get(options2).get(options3);

                textData.setText(tx);
//                Toast.makeText(PersonalInformationPage.this,tx,Toast.LENGTH_SHORT).show();
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this,"province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i=0;i<jsonBean.size();i++){//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c=0; c<jsonBean.get(i).getCityList().size(); c++){//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        ||jsonBean.get(i).getCityList().get(c).getArea().size()==0) {
                    City_AreaList.add("");
                }else {

                    for (int d=0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }


}
